package com.kaoqin.code.interceptor;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.kaoqin.code.util.AuthorUtils;
import com.kaoqin.code.util.DESUtils;
import com.kaoqin.code.util.StringUtil;
import com.kaoqin.model.Sign;
import com.kaoqin.model.SignLog;
import com.kaoqin.model.SysLog;
import com.kaoqin.model.User;
import com.kaoqin.service.SignLogService;
import com.kaoqin.service.SignService;
import com.kaoqin.service.SysLogService;
import com.kaoqin.service.UserService;

import net.sf.json.JSONObject;

/**
 * 登录认证的拦截器
 */
public class LoginInterceptor implements HandlerInterceptor {
	Logger log = Logger.getLogger(LoginInterceptor.class);
	private static Map<String,String> urlMap = new HashMap<String,String>();
	private static List<String> dataList = new ArrayList<String>();
	private UserService userService;
	private SysLogService sysLogService;
	@Autowired
	private SignLogService signLogService;
	
	public SysLogService getSysLogService() {
		return sysLogService;
	}
	public void setSysLogService(SysLogService sysLogService) {
		this.sysLogService = sysLogService;
	}
	/**
	 * @return the userService
	 */
	public UserService getUserService() {
		return userService;
	}
	/**
	 * @param userService the userService to set
	 */
	public void setUserService(UserService userService) {
		this.userService = userService;
	}
	static {
        //如果请求中包含以下路径，则不进行拦截   
		urlMap.put("/kaoqin/sign/list", null);
		urlMap.put("/kaoqin/sign/signClick", null);
		urlMap.put("/kaoqin/sign/signDetails", null);
		urlMap.put("/kaoqin/user/login", null);
		urlMap.put("/js", null);
		urlMap.put("/css", null);
		urlMap.put("/img", null);
		urlMap.put("/kaoqin/user/quit", null);
		
		dataList.add("/sign/updateSignLog");
	}
	/**
	 * Handler执行之前调用这个方法
	 */
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		String ip = AuthorUtils.getIpAddr(request);
		String requestURI = request.getRequestURI();
		for (String url : urlMap.keySet()) {
			if(requestURI.contains(url)) {
				return true;
			}
		}
		DESUtils des = AuthorUtils.getDESToken();
		String token = AuthorUtils.getToken(request);
		if(StringUtils.isNotBlank(token)) {
			token=des.decrypt(token);
		}
		User user = new User();
		user.setUserIp(AuthorUtils.getIpAddr(request));
		user.setLimitSql(" limit 0,1");
		User ipUser = userService.findByIp(user);
		log.info("============登录信息："+ipUser.toString()+"=========访问URL:"+requestURI+"===token:"+token);
		if(ipUser!=null && !"".equals(token)) {
			String password = ipUser.getUserPassword();
			String decrypt = des.decrypt(password);
			if(decrypt.equals(token)) {
				String editData=null;
				Integer opEditId=null;
				String opType="";
				if(requestURI.contains("/sign/updateSignLog")) {
					editData=StringUtil.getInterceptorParamStr(request);
					requestURI="更新数据";
					opType="edit";
				}
				if(requestURI.contains("/sign/editSignLogDel")) {
					editData=StringUtil.getInterceptorParamStr(request);
					requestURI="删除数据";
					opType="del";
				}
				if(StringUtils.isNotBlank(editData)&&"edit".equals(opType)) {
					JSONObject jsonO = JSONObject.fromObject(editData);
					String id = jsonO.getString("更新Id");
					if(StringUtils.isNotBlank(id)) {
						opEditId=Integer.parseInt(id);
					}
				}
				if(StringUtils.isNotBlank(editData)&&"del".equals(opType)) {
					JSONObject jsonO = JSONObject.fromObject(editData);
					String id = jsonO.getString("eId");
					if(StringUtils.isNotBlank(id)) {
						opEditId=Integer.parseInt(id);
						SignLog sign = signLogService.findSignLogById(opEditId);
						editData=new Gson().toJson(sign);
					}
				}
				getSysLog(requestURI,ip,0,Integer.parseInt(ipUser.getId()+""),editData,opEditId,opType);
				return true;
			}
		}
		//getSysLog(requestURI,ip,1,null,null,null);
		//不符合条件的，跳转到登录界面  
		request.getRequestDispatcher("/WEB-INF/jsp/login/login.jsp").forward(request, response);
		return false;
	}
	private void getSysLog(String requestURI, String ip, int isF,Integer userid,String edit,Integer opEditId, String opType) {
		SysLog logO=new SysLog();
		logO.setOpFunctionUrl(requestURI);
		logO.setOpIp(ip);
		logO.setOpIllegal(isF);
		logO.setOpUserId(userid);
		logO.setOpDate(new Date());
		logO.setOpEditData(edit);
		logO.setOpEditId(opEditId);
		logO.setOpType("".equals(opType) ? "login" : opType);
		sysLogService.insertOne(logO);
	}
	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
	}
	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
		// TODO Auto-generated method stub
	}
}
